<template>
  <div class="app-container">
    <!-- 页首导航 -->
    <el-header class="header">
      <div class="logo">
        <img src="@/assets/logo/logo.png" alt="在线课程教学平台" />
        <h1>在线课程教学平台</h1>
      </div>
      <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
        <el-menu-item index="1">首页</el-menu-item>
        <el-submenu index="2">
          <template slot="title">课程分类</template>
          <el-menu-item index="2-1">编程开发</el-menu-item>
          <el-menu-item index="2-2">设计创意</el-menu-item>
          <el-menu-item index="2-3">商业管理</el-menu-item>
          <el-menu-item index="2-4">职业技能</el-menu-item>
        </el-submenu>
        <el-menu-item index="3">最新课程</el-menu-item>
        <el-menu-item index="4">热门课程</el-menu-item>
        <el-menu-item index="5">关于我们</el-menu-item>
      </el-menu>

      <div class="login-register">
        <template v-if="!isLogin">
          <el-button type="text" @click="goToLogin">登录</el-button>
          <el-button type="primary" @click="goToRegister">注册</el-button>
        </template>
        <el-dropdown v-else class="avatar-container right-menu-item hover-effect" trigger="hover">
          <div class="avatar-wrapper">
            <img :src="avatar" class="user-avatar">
            <span class="user-nickname">{{ nickName }}</span>
          </div>
          <el-dropdown-menu slot="dropdown">
            <router-link to="/user/profile">
              <el-dropdown-item>个人中心</el-dropdown-item>
            </router-link>
            <el-dropdown-item divided @click.native="logout">
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <div class="search-box">
        <el-input placeholder="搜索课程..." v-model="searchText" suffix-icon="el-icon-search" @keyup.enter.native="handleSearch"></el-input>
      </div>
    </el-header>

    <!-- 课程轮播图 -->
    <el-carousel height="400px" indicator-position="outside">
      <el-carousel-item v-for="item in carouselItems" :key="item.id">
        <img :src="item.imageUrl" alt="课程轮播" class="carousel-img">
        <div class="carousel-caption">
          <h3>{{ item.title }}</h3>
          <p>{{ item.description }}</p>
          <el-button type="primary" @click="goToCourseDetail(item.courseId)">查看课程</el-button>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 主要内容区 -->
    <el-main class="main-content">
      <!-- 推荐课程 -->
      <section class="course-section">
        <div class="section-header">
          <h2>推荐课程</h2>
          <el-button type="text" class="more-btn" @click="handleShowAll('recommended')">查看全部 <i class="el-icon-arrow-right"></i></el-button>
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in displayRecommendedCourses" :key="course.id">
            <course-card :course="course" @click.native="goToCourseDetail(course.courseId)"></course-card>
          </el-col>
        </el-row>
      </section>

      <!-- 课程分类 -->
      <section class="course-section">
        <div class="section-header">
          <h2>课程分类</h2>
        </div>
        <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
          <el-tab-pane label="全部课程" name="all"></el-tab-pane>
          <el-tab-pane label="编程开发" name="programming"></el-tab-pane>
          <el-tab-pane label="设计创意" name="design"></el-tab-pane>
          <el-tab-pane label="商业管理" name="business"></el-tab-pane>
          <el-tab-pane label="职业技能" name="skills"></el-tab-pane>
        </el-tabs>
        
        <div class="course-filter">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
            <el-option label="最新发布" value="publishTime"></el-option>
            <el-option label="注册人数" value="studentCount"></el-option>
            <el-option label="更新时间" value="updateTime"></el-option>
            <el-option label="点赞人数" value="likeCount"></el-option>
          </el-select>
          <el-select v-model="sortOrder" placeholder="排序顺序" @change="handleSortChange">
            <el-option label="升序" value="asc"></el-option>
            <el-option label="降序" value="desc"></el-option>
          </el-select>
        </div>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in filteredCourses" :key="course.id">
            <course-card :course="course"></course-card>
          </el-col>
        </el-row>
      </section>

      <!-- 热门课程 -->
      <section class="course-section">
        <div class="section-header">
          <h2>热门课程</h2>
          <el-button type="text" class="more-btn" @click="handleShowAll('popular')">查看全部 <i class="el-icon-arrow-right"></i></el-button>
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in displayPopularCourses" :key="course.id" @click.native="goToCourseDetail(course.courseId)">
            <course-card :course="course"></course-card>
          </el-col>
        </el-row>
      </section>

      <!-- 最新课程 -->
      <section class="course-section">
        <div class="section-header">
          <h2>最新课程</h2>
          <el-button type="text" class="more-btn" @click="handleShowAll('latest')">查看全部 <i class="el-icon-arrow-right"></i></el-button>
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in displayLatestCourses" :key="course.id" @click.native="goToCourseDetail(course.courseId)">
            <course-card :course="course"></course-card>
          </el-col>
        </el-row>
      </section>
    </el-main>

    <!-- 页脚 -->
    <el-footer class="footer">
      <div class="footer-content">
        <div class="footer-column">
          <h3>关于我们</h3>
          <p>在线课程教学平台致力于提供高质量的在线教育资源，帮助学习者实现自我提升。</p>
        </div>
        <div class="footer-column">
          <h3>联系我们</h3>
          <p>邮箱：contact@example.com</p>
          <p>电话：400-123-4567</p>
        </div>
        <div class="footer-column">
          <h3>快速链接</h3>
          <ul>
            <li><a href="#">帮助中心</a></li>
            <li><a href="#">隐私政策</a></li>
            <li><a href="#">服务条款</a></li>
          </ul>
        </div>
      </div>
      <div class="copyright">
        <p>Copyright © 2023 在线课程教学平台 All Rights Reserved.</p>
      </div>
    </el-footer>
  </div>
</template>

<script>
import CourseCard from '@/components/Course/CourseCard.vue'
import { listRecords, getRecordsByCourseId,searchCoursesByName } from "@/api/course/records"
import { mapGetters } from 'vuex'

export default {
  name: 'IndexAll',
  computed: {
    ...mapGetters([
      'avatar',
      'nickName',
      'token' // 添加 token 作为登录状态判断依据
    ]),
    isLogin() {
      return this.token && this.token !== ''
    },
    staticRecommendedCourses() {
      return [
        ...this.staticPopularCourses,
        ...this.staticLatestCourses
      ]
    },
    displayRecommendedCourses() {
      return this.isLogin ? this.recommendedCourses : this.staticRecommendedCourses
    },
    displayPopularCourses() {
      return this.isLogin ? this.popularCourses : this.staticPopularCourses
    },
    displayLatestCourses() {
      return this.isLogin ? this.latestCourses : this.staticLatestCourses
    }
  },
  components: {
    CourseCard
  },
  created() {
    this.loadCourseData() // 直接调用无需登录校验
  },
  data() {
    return {
      activeIndex: '1',
      searchText: '',
      activeCategory: 'all',
      sortBy: 'publishTime',
      sortOrder: 'desc',    
      carouselItems: [
          {
          id: 1,
          title: 'Python-大模型应用',
          description: '从入门到精通，成为全栈开发工程师',
          imageUrl: require('@/assets/course/course_img/CS/Python.png'), // 添加require
          courseId: 100
        },
        {
          id: 2,
          title: 'Java编程',
          description: '使用Java进行数据分析与可视化实战',
          imageUrl: require('@/assets/course/course_img/CS/Java.png'),
          courseId: 101
        },
        {
          id: 3,
          title: '软件工程',
          description: '掌握现代界面设计与用户体验设计精髓',
          imageUrl: require('@/assets/course/course_img/CS/Software-engineer.png'),
          courseId: 102
        },
      ],
      staticPopularCourses: [
        {
          courseId: 102,
          courseName: '软件工程',
          teacherName: '杜老师',
          teacherUniversity: '深圳大学',
          credit: 4,
          capacity: 40,
          teacherAvatar: 'avatar/teachers/DuWenFeng.jpg',
          courseCover: 'course/course_img/CS/Software-engineer.png',
          semester: '2023-2024春季',
          courseIntro: '课程基于IEEE最新版SWEBOK知识体系...'
        },
        {
          courseId: 103,
          courseName: '数据库技术',
          teacherName: '杜老师',
          teacherUniversity: '深圳大学',
          credit: 3,
          capacity: 50,
          teacherAvatar: 'avatar/teachers/DuWenFeng.jpg',
          courseCover: 'course/course_img/CS/Database.png',
          semester: '2023-2024春季',
          courseIntro: '课程分为三大模块...'
        }
      ],
      staticLatestCourses: [
        {
          courseId: 200,
          courseName: '高等数学A',
          teacherName: '顾教授',
          teacherUniversity: '浙江大学',
          credit: 5,
          capacity: 50,
          teacherAvatar: 'avatar/teachers/XiongWeiDan.jpg',
          courseCover: 'course/course_img/MATH/Higher_mathematics.png',
          semester: '2023-2024全年',
          courseIntro: '采用"问题驱动"教学法...'
        },
        {
          courseId: 201,
          courseName: '线性代数',
          teacherName: '梁教授',
          teacherUniversity: '哈尔滨工业大学',
          credit: 4,
          capacity: 60,
          teacherAvatar: 'avatar/teachers/ZhangYang.jpg',
          courseCover: 'course/course_img/MATH/Linear_algebra.png',
          semester: '2023-2024秋季',
          courseIntro: '课程突出计算机应用特色...'
        }
      ],
      recommendedCourses: [],
      popularCourses: [],
      latestCourses: [],
      filteredCourses: [],
      allCourses: [], // 添加初始化
    }
  },
  methods: {
    handleSelect(key) {
      // 菜单选择处理逻辑
      console.log('Selected:', key);
    },
    loadCourseData() {
      // 单次获取全量数据
      listRecords().then(response => {
        const allCourses = response.rows;
        
        // 推荐课程处理逻辑（按学分降序排列）
        this.recommendedCourses = [...allCourses]
          .sort((a, b) => b.credit - a.credit) // 按学分降序
          .slice(0, 4) // 取前4门课程

        // 处理热门课程（按访问量降序）
        this.popularCourses = [...allCourses]
          .sort((a, b) => b.capacity - a.capacity)
          .sort(() => Math.random() - 0.5) // 新增随机排序
          .slice(0, 4) // 取前4门课程

        // 处理最新课程（按创建时间降序）
        this.latestCourses = [...allCourses]
          .sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
          .slice(0, 4) // 取前4门课程

        // 初始化分类数据
        this.handleCategoryChange(allCourses);
      });
    },
    // 查看全部课程
    handleShowAll(type) {
      listRecords().then(response => {
        const allCourses = response.rows;
        switch(type) {

          case 'recommended':
            this.recommendedCourses = [...allCourses]
              .sort((a, b) => b.credit - a.credit) // 按学分降序
            break;

          case 'popular':
            this.popularCourses = [...allCourses]
              .sort((a, b) => b.capacity - a.capacity)
              .sort(() => Math.random() - 0.5) // 新增随机排序
            break;

          case 'latest':
            this.latestCourses = [...allCourses]
              .sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
            break;
        }
    })
    },

    goToLogin() {
      this.$router.push('/login')
    },
    goToRegister() {
      this.$router.push('/register')
    },
    // handleSearch() {
    //   // 处理搜索逻辑
    //   this.$router.push({ path: '/course/search', query: { keyword: this.searchText } })
    // },
      handleSearch() {
    if (!this.searchText.trim()) {
      this.$message.warning('请输入搜索内容');
      return;
    }
    searchCoursesByName(this.searchText.value).then(response => {
      this.$router.push({
        path: '/course/search',
        query: {
          keyword: this.searchText,
          results: JSON.stringify(response.rows)
        }
      });
    }).catch(error => {
      console.error('搜索失败:', error);
      this.$message.error('搜索失败');
    });
  },
    goToCourseDetail(courseId) {
      this.$router.push(`/course/detail/${courseId}`)
    },
    handleCategoryChange() {
      // 使用本地数据过滤
      this.filteredCourses = this.allCourses.filter(c => {
        if (this.activeCategory === 'all') return true;
        return c.categoryId === this.activeCategory;
      }).sort((a, b) => {
        const modifier = this.sortOrder === 'asc' ? 1 : -1;
        return (a[this.sortBy] > b[this.sortBy]) ? modifier : -modifier;
      });
    },
    handleSortChange() {
      // 根据排序条件对课程进行排序
      this.filteredCourses.sort((a, b) => {
        if (this.sortOrder === 'asc') {
          return a[this.sortBy] > b[this.sortBy] ? 1 : -1
        } else {
          return a[this.sortBy] < b[this.sortBy] ? 1 : -1
        }
      })
    },

    logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          // location.href = '/index'
          // 回到主页
          location.href = '/'
        })
      }).catch(() => {})
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .logo {
    display: flex;
    align-items: center;
    
    img {
      height: 40px;
      margin-right: 10px;
    }
    
    h1 {
      font-size: 24px;
      margin: 0;
      color: #1890ff;
    }
  }
  
  .login-register {
    margin-left: auto;
    margin-right: 20px;
    
    button {
      margin-left: 10px;
    }
  }
  
  .search-box {
    width: 300px;
    margin-left: 20px;
  }
}

.app-container {
  transform-origin: top center;
  // transform: scale(0.8);
  width: 100%;
}

.el-carousel {
  margin-bottom: 30px;
  
  .carousel-img {
    width: 100%;
    height: 400px;
    object-fit: cover;
  }
  
  .carousel-caption {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
    color: white;
    
    h3 {
      font-size: 24px;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 16px;
      margin-bottom: 15px;
    }
  }
}

.main-content {
  padding: 20px;
  
  .course-section {
    margin-bottom: 40px;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h2 {
        font-size: 22px;
        color: #333;
        border-left: 4px solid #1890ff;
        padding-left: 10px;
      }
      
      .more-btn {
        color: #1890ff;
      }
    }
    
    .course-filter {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 20px;
      
      .el-select {
        margin-left: 10px;
        width: 150px;
      }
    }
  }
}

.footer {
  background-color: #f5f5f5;
  padding: 40px 0 20px;
  
  .footer-content {
    display: flex;
    justify-content: space-around;
    margin-bottom: 30px;
    
    .footer-column {
      width: 25%;
      
      h3 {
        font-size: 18px;
        margin-bottom: 15px;
        color: #333;
      }
      
      p {
        color: #666;
        line-height: 1.6;
      }
      
      ul {
        list-style: none;
        padding: 0;
        
        li {
          margin-bottom: 8px;
          
          a {
            color: #666;
            text-decoration: none;
            
            &:hover {
              color: #1890ff;
            }
          }
        }
      }
    }
  }
  
  .copyright {
    text-align: center;
    color: #999;
    padding-top: 20px;
    border-top: 1px solid #e5e5e5;
  }
}


// 新增样式（从 Navbar.vue 迁移）
.avatar-container {
  margin-right: 0px;
  padding-right: 0px;

  .avatar-wrapper {
    margin-top: 10px;
    position: relative;

    .user-avatar {
      cursor: pointer;
      width: 30px;
      height: 30px;
      border-radius: 50%;
    }

    .user-nickname {
      position: relative;
      bottom: 10px;
      font-size: 14px;
      font-weight: bold;
    }
  }
}
</style>